
import { FormInstance, Tooltip } from 'antd';
import { Button, Table, Space, message, Divider, Popconfirm, Card } from 'antd';
import { ModalForm } from '@ant-design/pro-form';

import React, { useRef, useState, useEffect, Fragment } from 'react';
import { ProFormText, ProFormSelect, ProFormDigit, ProFormSwitch } from '@ant-design/pro-form';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import Authorized, { includesKey } from '@/components/Authorized';
// import { layoutActionRef } from '@/app';

// 菜单页面
const SysMenu: React.FC = ({ sysMenu, dispatch }: {
  sysMenu: any;
  dispatch: any;
}) => {

  /** 新建窗口的弹窗 */
  const formRef = useRef<FormInstance>();
  // 弹窗
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  // 树数据
  const [data, setData] = useState([]);
  // 页面id
  const [id, setId] = useState<string>();
  // 上级id
  const [parentId, setParentId] = useState<string>();

  const [type, setType] = useState<number>(0);


  // 页面初次加载
  useEffect(() => {
    findMenuTree();
  }, []);

  // 新增下级弹窗
  const addSubordinate = (record) => {
    const recordData = {
      parentName: record.name
    }
    setParentId(record.id);
    setId(undefined);
    formRef?.current?.resetFields();
    formRef?.current?.setFieldsValue(recordData);

    handleModalVisible(true);
  };

  // 修改弹窗
  const edit = (record) => {
    const recordData = {
      ...record,
      state: record.state !== 1
    }
    setId(record.id);
    setType(record.type);
    setParentId(record.parentId);
    formRef?.current?.setFieldsValue(recordData);
    handleModalVisible(true);
  };

  // 删除
  const deleteRecord = (record) => {
    const hide = message.loading('操作中');
    dispatch({
      type: 'sysMenu/fakeDelete',
      payload: record.id,
      callback: (res) => {
        if (res.code === 1) {
          hide();
          message.success('操作成功');
          findMenuTree();

        } else {
          hide();
          handleModalVisible(false);
          message.error('操作失败请重试！');
          return false;
        }

      }
    });
  };

  // 获取树数据
  const findMenuTree = () => {
    dispatch({
      type: 'sysMenu/findMenuTree',
      payload: {},
      callback: (res) => {
        if (res.code === 1) {
          setData(res.data);
        }

      }
    });
  };

  // 弹出层保存
  const handleAdd = (fields) => {
    const hide = message.loading('操作中');
    const data = {
      ...fields,
      id,
      parentId,
      state: fields.state ? 0 : 1,
    }
    try {
      dispatch({
        type: id ? 'sysMenu/updateObject' : 'sysMenu/saveObject',
        payload: data,
        callback: (res) => {
          if (res.code === 1) {
            hide();
            handleModalVisible(false);
            message.success('操作成功');
            findMenuTree();
            // 手动刷新菜单
            // layoutActionRef?.current?.reload();

          } else {
            hide();
            handleModalVisible(false);
            message.error('操作失败请重试！');
            return false;
          }

        }
      });

    } catch (error) {
      hide();
      handleModalVisible(false);
      message.error('操作失败请重试！');
      return false;
    }
  };

  // 栏目
  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '菜单URL',
      dataIndex: 'url',
      key: 'url',

    },
    {
      title: '授权',
      dataIndex: 'permission',
      key: 'permission',

    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (record) => {
        if (record == 0) {
          return "目录";
        } else if (record == 1) {
          return "菜单";
        } else if (record == 2) {
          return "按钮";
        }
      }
    },

    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (record) => {
        if (record == 0) {
          return "开启";
        } else if (record == 1) {
          return "禁用";
        }
      }
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },

  ];
  includesKey(columns, ["menu:save", "menu:update", "menu:delete"], {
    title: '操作',
    dataIndex: 'Action',
    key: 'Action',
    render: (text, record) => (
      <Space size={0}>
        <Authorized authority="menu:save">
          {
            record.type != 2 ?
              <Fragment>
                <Button type="link" onClick={() =>
                  addSubordinate(record)}>
                  新增下级
                </Button>
                <Divider type="vertical" />
              </Fragment>

              :
              ''
          }
        </Authorized>

        <Authorized authority="menu:update">
          <Button type="link" onClick={() =>

            edit(record)}>
            修改
          </Button>
        </Authorized>
        <Divider type="vertical" />
        <Authorized authority="menu:delete">
          <Popconfirm title="确定删除吗?" onConfirm={() => deleteRecord(record)}>
            <Button type="link" >删除</Button>
          </Popconfirm>
        </Authorized>


      </Space>
    )
  });

  // 页面样式
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  return (
    <div>
      <Authorized authority="menu:save">
        <Button
          type="primary"
          key="primary"
          onClick={() => {
            formRef?.current?.resetFields();
            setId(undefined);
            setParentId(undefined);
            handleModalVisible(true);
            setType(0);
          }}
        >
          <PlusOutlined /> 新建
        </Button>
      </Authorized>
      <Table
        style={{ marginTop: '20px' }}
        pagination={false}
        columns={columns}
        rowKey="id"
        dataSource={data}
      />

      <ModalForm
        title={id ? "修改" : "新增"}
        modalProps={{
          maskClosable: false,
        }}
        // width="400px"
        {...formItemLayout}
        layout={'horizontal'}
        formRef={formRef}
        initialValues={{
          sort: 999,
          parentName: "无",
          type: 0
        }}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {

          const success = await handleAdd(value as API.RuleListItem);
          if (success) {
            handleModalVisible(false);
          }
        }}
      >

        <ProFormText

          label="上级"
          width="md"
          name="parentName"
          disabled
        />

        <ProFormText
          rules={[
            {
              max: 20,
              min: 1,
              required: true,
              message: '请输入1-20个字符！',
            },
          ]}
          label="菜单名称"
          width="md"
          name="name"
        />

        <ProFormSelect
          width="md"
          rules={[
            {
              required: true,
              message: '请选择类型！',
            },
          ]}
          options={[
            {
              value: 0,
              label: '目录',
            },
            {
              value: 1,
              label: '菜单',
            },
            {
              value: 2,
              label: '按钮',
            },
          ]}
          name="type"
          label="类型"
          fieldProps={{// 这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
            onChange: (val) => {
              formRef?.current?.setFieldsValue({ url: '' });
              setType(val);
            },
          }}

        />
        {/* 菜单必填 */}

        <ProFormText
          rules={type === 1 ? [
            {
              max: 50,
              min: 1,
              required: true,
              message: '请输入1-50个字符！',
            },
          ] : []}
          label={<Tooltip title="必须是 /pages/[url]/index.tsx 中的 url 值">url</Tooltip>}
          width="md"
          name="url"
          placeholder="必须是 /pages/[url]/index.tsx 中的 url 值"
          disabled={type === 2}
        />

        {/* 菜单必填 */}
        {/* <ProFormText
            rules={type === 1 ? [
              {
                max: 50,
                min: 1,
                required: true,
                message: '请输入1-50个字符！',
              },
            ] : []}
            label="组件地址"
            width="md"
            name="component"
            disabled={type === 2}
          /> */}



        <ProFormText
          rules={type === 1 ? [
            {
              max: 30,
              min: 1,
              message: '请输入1-20个字符！',
            },
          ] : []}
          label="授权"
          width="md"
          name="permission"
        />

        <ProFormText
          rules={[
            {
              max: 60,
              min: 0,
              message: '请输入0-60个字符！',
            },
          ]}
          label="菜单图标"
          width="md"
          name="icon"
        />

        <ProFormDigit
          rules={[
            {
              required: true,
              message: '请输入排序！',
            },
          ]}

          min={0} max={999}
          label="排序"
          width="md"
          name="sort"
        />

        <ProFormSwitch label="状态" name="state" />

      </ModalForm>



    </div>
  );
}
export default connect(
  ({ sysMenu, loading }: { index: any; loading: any }) => ({
    sysMenu,
    loading: loading.models.sysMenu,
  }),
)(SysMenu);
